﻿
namespace Anycmd.AC.Web.Mvc.Controllers
{
    using Anycmd.Host.AC;
    using Anycmd.Repositories;
    using Anycmd.Web.Mvc;
    using Exceptions;
    using Host;
    using Host.AC.Messages;
    using Host.AC.ValueObjects;
    using MiniUI;
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Web.Mvc;
    using Util;
    using ViewModel;
    using ViewModels.DSDSetViewModels;

    public class DSDSetController : AnycmdController
    {
        private readonly EntityTypeState dsdSetEntityType;

        public DSDSetController()
        {
            if (!Host.EntityTypeSet.TryGetEntityType("AC", "DSDSet", out dsdSetEntityType))
            {
                throw new CoreException("意外的实体类型");
            }
        }

        [By("xuexs")]
        [Description("动态职责分离角色集")]
        public ViewResultBase Index()
        {
            return ViewResult();
        }

        [By("xuexs")]
        [Description("动态职责分离角色集详细信息")]
        public ViewResultBase Details()
        {
            if (!string.IsNullOrEmpty(Request["isTooltip"]))
            {
                Guid id;
                if (Guid.TryParse(Request["id"], out id))
                {
                    var data = dsdSetEntityType.GetData(id);
                    return new PartialViewResult { ViewName = "Partials/Details", ViewData = new ViewDataDictionary(data) };
                }
                else
                {
                    throw new ValidationException("非法的Guid标识" + Request["id"]);
                }
            }
            else if (!string.IsNullOrEmpty(Request["isInner"]))
            {
                return new PartialViewResult { ViewName = "Partials/Details" };
            }
            else
            {
                return this.View();
            }
        }

        [By("xuexs")]
        [Description("动态职责分离角色集角色列表")]
        public ViewResultBase Roles()
        {
            return ViewResult();
        }

        [By("xuexs")]
        [Description("根据ID获取动态职责分离角色集")]
        public ActionResult Get(Guid? id)
        {
            if (!id.HasValue)
            {
                throw new ValidationException("未传入标识");
            }
            return this.JsonResult(dsdSetEntityType.GetData(id.Value));
        }

        [By("xuexs")]
        [Description("根据ID获取动态职责分离角色集详细信息")]
        public ActionResult GetInfo(Guid? id)
        {
            if (!id.HasValue)
            {
                throw new ValidationException("未传入标识");
            }
            return this.JsonResult(dsdSetEntityType.GetData(id.Value));
        }

        [By("xuexs")]
        [Description("分页获取动动态职责分离角色集列表")]
        public ActionResult GetPlistDSDSets(GetPlistResult requestModel)
        {
            if (!ModelState.IsValid)
            {
                return ModelState.ToJsonResult();
            }
            var data = Host.GetPlistDSDSets(requestModel);

            return this.JsonResult(new MiniGrid<DSDSetTr> { total = requestModel.total.Value, data = data });
        }

        #region AddOrDeleteRoleMembers
        [By("xuexs")]
        [Description("加入或删除角色")]
        [HttpPost]
        public ActionResult AddOrDeleteRoleMembers()
        {
            String json = Request["data"];
            var rows = (ArrayList)MiniJSON.Decode(json);
            foreach (Hashtable row in rows)
            {
                var id = new Guid(row["Id"].ToString());
                //根据记录状态，进行不同的增加、删除、修改操作
                String state = row["_state"] != null ? row["_state"].ToString() : "";

                //更新：_state为空或modified
                if (state == "modified" || state == "")
                {
                    bool isAssigned = bool.Parse(row["IsAssigned"].ToString());
                    var entity = GetRequiredService<IRepository<DSDRole>>().GetByKey(id);
                    if (entity != null)
                    {
                        if (!isAssigned)
                        {
                            Host.Handle(new RemoveDSDRoleCommand(id));
                        }
                    }
                    else if (isAssigned)
                    {
                        var createInput = new DSDRoleCreateInput
                        {
                            Id = new Guid(row["Id"].ToString()),
                            RoleID = new Guid(row["RoleID"].ToString()),
                            DSDSetID = new Guid(row["DSDSetID"].ToString())
                        };
                        Host.Handle(new AddDSDRoleCommand(createInput));
                    }
                }
            }

            return this.JsonResult(new ResponseData { success = true });
        }
        #endregion

        [By("xuexs")]
        [Description("创建动态职责分离角色集")]
        [HttpPost]
        public ActionResult Create(DSDSetCreateInput input)
        {
            if (!this.ModelState.IsValid)
            {
                return this.ModelState.ToJsonResult();
            }
            Host.Handle(new AddDSDSetCommand(input));

            return this.JsonResult(new ResponseData { success = true, id = input.Id });
        }

        [By("xuexs")]
        [Description("更新动态职责分离角色集")]
        [HttpPost]
        public ActionResult Update(DSDSetUpdateInput input)
        {
            if (!this.ModelState.IsValid)
            {
                return this.ModelState.ToJsonResult();
            }
            Host.Handle(new UpdateDSDSetCommand(input));

            return this.JsonResult(new ResponseData { success = true, id = input.Id });
        }

        [By("xuexs")]
        [Description("删除动态职责分离角色集")]
        [HttpPost]
        public ActionResult Delete(string id)
        {
            string[] ids = id.Split(',');
            var idArray = new Guid[ids.Length];
            for (int i = 0; i < ids.Length; i++)
            {
                Guid tmp;
                if (Guid.TryParse(ids[i], out tmp))
                {
                    idArray[i] = tmp;
                }
                else
                {
                    throw new ValidationException("意外的动态职责分离角色集标识" + ids[i]);
                }
            }
            foreach (var item in idArray)
            {
                Host.Handle(new RemoveDSDSetCommand(item));
            }

            return this.JsonResult(new ResponseData { id = id, success = true });
        }
    }
}
